import { createRouter, createWebHistory } from "vue-router";
import { useAuth } from "@/composables/useAuth";
import { ElMessage } from "element-plus";

// 路由组件懒加载
const LoginView = () => import("@/views/auth/LoginView.vue");
const RegisterView = () => import("@/views/auth/RegisterView.vue");
const ChatView = () => import("@/views/chat/ChatView.vue");
const PersonaView = () => import("@/views/persona/PersonaView.vue");
const SettingsView = () => import("@/views/settings/SettingsView.vue");

// 路由配置
const routes = [
  {
    path: "/",
    redirect: "/chat",
  },
  {
    path: "/login",
    name: "Login",
    component: LoginView,
    meta: {
      title: "登录",
      requiresAuth: false,
      hideForAuth: true, // 已登录用户隐藏
    },
  },
  {
    path: "/register",
    name: "Register",
    component: RegisterView,
    meta: {
      title: "注册",
      requiresAuth: false,
      hideForAuth: true,
    },
  },
  {
    path: "/chat",
    name: "Chat",
    component: ChatView,
    meta: {
      title: "聊天",
      requiresAuth: true,
      keepAlive: true,
    },
  },
  {
    path: "/persona",
    name: "Persona",
    component: PersonaView,
    meta: {
      title: "人格管理",
      requiresAuth: true,
    },
  },
  {
    path: "/settings",
    name: "Settings",
    component: SettingsView,
    meta: {
      title: "设置",
      requiresAuth: true,
    },
  },
  {
    path: "/settings/:section",
    name: "SettingsSection",
    component: SettingsView,
    meta: {
      title: "设置",
      requiresAuth: true,
    },
  },
  // 404 页面
  {
    path: "/:pathMatch(.*)*",
    name: "NotFound",
    component: () => import("@/views/error/NotFoundView.vue"),
    meta: {
      title: "页面未找到",
    },
  },
];

// 创建路由实例
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
  scrollBehavior(to, from, savedPosition) {
    // 路由切换时的滚动行为
    if (savedPosition) {
      return savedPosition;
    } else {
      return { top: 0 };
    }
  },
});

// 全局前置守卫
router.beforeEach(async (to, _from, next) => {
  const { isAuthenticated, checkAuth } = useAuth();

  // 设置页面标题
  if (to.meta.title) {
    document.title = `${to.meta.title} - CardcaptorSakura`;
  }

  // 检查认证状态
  if (!isAuthenticated.value) {
    try {
      await checkAuth();
    } catch (error) {
      // 认证失败，清除本地存储
      localStorage.removeItem("token");
      localStorage.removeItem("refreshToken");
    }
  }

  // 路由权限控制
  if (to.meta.requiresAuth && !isAuthenticated.value) {
    // 需要认证但未登录，跳转到登录页
    ElMessage.warning("请先登录");
    next({
      name: "Login",
      query: { redirect: to.fullPath },
    });
    return;
  }

  if (to.meta.hideForAuth && isAuthenticated.value) {
    // 已登录用户访问登录/注册页，跳转到首页
    next({ name: "Chat" });
    return;
  }

  next();
});

// 全局后置守卫
router.afterEach((_to, _from) => {
  // 路由切换完成后的处理
  // 可以在这里添加页面访问统计等逻辑
});

// 路由错误处理
router.onError((error) => {
  // 路由错误
  ElMessage.error("页面加载失败，请刷新重试");
});

export default router;

// 导出路由相关工具函数
export const getRouteTitle = (routeName: string): string => {
  const route = routes.find((r) => r.name === routeName);
  return route?.meta?.title || "";
};

export const isAuthRoute = (routeName: string): boolean => {
  const route = routes.find((r) => r.name === routeName);
  return route?.meta?.requiresAuth || false;
};

export const getAuthRoutes = () => {
  return routes.filter((route) => route.meta?.requiresAuth);
};

export const getPublicRoutes = () => {
  return routes.filter((route) => !route.meta?.requiresAuth);
};
